<template>
  <div>
    <!-- <el-form-item
      v-loading="loading"
      element-loading-text="上传中..."
      required=""
      label="课时视频"
    > -->
      <el-upload
        list-type="text"
        :http-request="fileChange"
        action
        accept="video/mp4"
        :on-success="videoPathSuccess"
        :on-remove="handleRemoveVideoPath"
        :drag="false"
        :limit="1"
        :file-list="videoPath"
        :auto-upload="true"
        :before-remove="beforeRemove"
      >
        <el-button size="small" type="primary">点击上传</el-button>
      </el-upload>
      <el-progress v-if="upflag" :percentage="authProgress"></el-progress>
      <span v-if="upflag">{{ statusText }}</span>
    <!-- </el-form-item> -->
  </div>
</template>
<script>
export default {
  data() {
    return {
      videoPath: [], //先导片
      thumbnailUrl: [], //缩略图
      upflag: false,
      loading: false,
      //超时时间
      timeout: 60000,
      //分片大小默认1M，不能小于100K
      partSize: "1048576",
      //并行上传分片个数，默认5
      parallel: 5,
      //网络原因失败时，重新上传次数，默认为3
      retryCount: 1,
      //网络原因失败时，重新上传间隔时间，默认为2秒
      retryDuration: 2,
      //上传到点播的地域 国内请填cn-shanghai
      region: "cn-beijing",
      //状态提示文本
      statusText: "正在准备",
      //上传进度
      authProgress: 0,
      //用户自定义标题
      title: "",
      //文件名称
      fileName: "",
      //阿里上传视频对象
      uploader: null,
      percentage: 0,
    };
  },
  methods: {
    videoPathSuccess(res, file, list) {
      this.form.videoPath = res.data;
    },
    handleRemoveVideoPath(file, fileList) {
      this.form.videoPath = "";
      this.$emit('getVideo',null)
      this.upflag = false;
    },
    //自定义上传功能
    fileChange(param) {
      param.percent = 10;
      this.file = param.file;
      let size = param.file.size / 1024 / 1024 < 5120;
      if (!this.file) {
        this.videoPath = [];
        this.$message.error("请先选择需要上传的文件！");
        return;
      }
      if (!size) {
        this.videoPath = [];
        this.$message.error("文件大小必须小于5GB！");
        return;
      }
      if (!this.form.chapterName) {
        this.videoPath = [];
        this.$message.error("请输入标题！");
        return;
      }
      this.fileName = this.file.name;
      let userData = '{"Vod":{"Title": "' + this.form.chapterName + '"}}';
      if (this.uploader) {
        this.uploader.stopUpload();
        this.authProgress = 0;
        this.statusText = "";
      }
      this.uploader = this.createUploader();
      this.uploader.addFile(this.file, null, null, null, userData);
      // 然后调用 startUpload 方法, 开始上传
      if (this.uploader !== null) {
        this.uploader.startUpload();
      }
    },
    createUploader(type) {
      //保存this
      let self = this;
      //创建阿里上传视频文件的对象
      let uploader = new AliyunUpload.Vod({
        //将参数赋值
        timeout: self.timeout,
        partSize: self.partSize,
        parallel: self.parallel,
        retryCount: self.retryCount,
        retryDuration: self.retryDuration,
        region: self.region,
        // userId: self.userId,
        // 添加文件成功
        addFileSuccess: function (uploadInfo) {
          self.statusText = "添加文件成功, 等待上传...";
        },
        // 开始上传
        onUploadstarted: function (uploadInfo) {
          console.log(11,uploadInfo)
          // debugger;
          // self.loading = true;
          self.upflag = true;
          self.$axios.getVideoToken({}).then(({ data }) => {
            console.log(22,data)
            uploader.setSTSToken(uploadInfo, data.akId, data.akScret, data.stk);
          });
          self.statusText = "文件开始上传...";
        },
        // 文件上传成功
        onUploadSucceed: function (uploadInfo) {
			console.log(uploadInfo)
          self.$emit("getVideo", {
            // name: uploadInfo.videoInfo.Title,
            videoId: uploadInfo.videoId,
            fileName: uploadInfo.file.name,
            fileSize:uploadInfo.file.size
          });
          self.form.videoPath = uploadInfo.videoId;
          self.statusText = "文件上传成功!";
          self.$message.success("上传成功");
          self.loading = false;
          setTimeout(() => {
            self.upflag = false;
          }, 1000);
        },
        // 文件上传失败
        onUploadFailed: function (uploadInfo, code, message) {
          //self.$store.commit('CLOSE_LOADING');
          self.statusText = "文件上传失败!";
          self.$message.error("上传失败，请尝试重新上传");
          self.loading = false;
          setTimeout(() => {
            self.upflag = false;
          }, 1000);
        },
        // 取消文件上传
        onUploadCanceled: function (uploadInfo, code, message) {
          //self.$store.commit('CLOSE_LOADING');
          self.statusText = "文件已暂停上传";
        },
        // 文件上传进度，单位：字节, 可以在这个函数中拿到上传进度并显示在页面上
        onUploadProgress: function (uploadInfo, totalSize, progress) {
          let progressPercent = Math.ceil(progress * 100);
          self.percentage = progressPercent;
          self.authProgress = progressPercent;
          self.statusText = "文件上传中...";
          // if (progressPercent == 100) {
          //   self.loading = false;
          // }
        },
        // 上传凭证超时
        onUploadTokenExpired: function (uploadInfo) {
          // 上传大文件超时, 如果是上传方式一即根据 UploadAuth 上传时
          // 需要根据 uploadInfo.videoId 调用刷新视频上传凭证接口(https://help.aliyun.com/document_detail/55408.html)重新获取 UploadAuth
          // 然后调用 resumeUploadWithAuth 方法, 这里是测试接口, 所以我直接获取了 UploadAuth
          let refreshUrl =
            "https://demo-vod.cn-shanghai.aliyuncs.com/voddemo/RefreshUploadVideo?BusinessType=vodai&TerminalType=pc&DeviceModel=iPhone9,2&UUID=59ECA-4193-4695-94DD-7E1247288&AppVersion=1.0.0&Title=haha1&FileName=xxx.mp4&VideoId=" +
            uploadInfo.videoId;
          axios.get(refreshUrl).then(({ data }) => {
            let uploadAuth = data.UploadAuth;
            uploader.resumeUploadWithAuth(uploadAuth);
          });
          self.statusText = "文件超时...";
          self.loading = false;
        },
        // 全部文件上传结束
        onUploadEnd: function (uploadInfo) {
          self.statusText = "文件上传完毕";
          self.loading = false;
        },
      });
      return uploader;
    },
    beforeRemove() {
      return this.$confirm("确认关闭？");
    }
  },
  props: ["form", "VideoList"],
  mounted() {
    this.videoPath = this.VideoList;
  },
  watch:{
    VideoList:{
      handler(newName,oldName){
        this.videoPath=newName
      },
      deep:true
    }
  }
};
</script>